package com.moqianfan.mcuassistant.utils;

import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.List;

public class GsonUtils {
    private static Gson gson = null;

    static {
        if (gson == null) {
            gson = new Gson();
        }
    }

    private GsonUtils() {
    }

    /**
     * Bean转String
     *
     * @param object Bean
     * @return String Result
     */
    public static String GsonString(Object object) {
        String gsonString = null;
        if (gson != null) {
            gsonString = gson.toJson(object);
        }
        return gsonString;
    }

    /**
     * String转Bean
     *
     * @param gsonString 要转换的jsonString
     * @param cls        Bean
     * @return 转换结果
     */
    public static <T> T GsonToBean(String gsonString, Class<T> cls) {
        T t = null;
        if (gson != null) {
            t = gson.fromJson(gsonString, cls);
        }
        return t;
    }

    /**
     * Bean转String
     *
     * @param allObject Bean
     * @return String Result
     */
    public static String GsonString(List<Object> allObject) {
        JSONArray array = new JSONArray();
        for (Object item : allObject) {
            array.put(GsonString(item));
        }
        return array.toString();
    }
}
